package com.shoesmail.utils;

import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @author ：xxx
 * @description：TODO
 * @date ：2025/9/17 20:52
 */
@Component
public class MinioUtil {
    private final MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucket;

    public MinioUtil(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    // 上传文件
    public void upload(String phoneName, InputStream stream, String contentType) throws Exception {
        // 确保 bucket 存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }

        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucket) //桶名称
                        .object(phoneName) //文件名
                        .stream(stream, stream.available(), -1)
                        .contentType(contentType)
                        .build()
        );
    }

    // 下载文件
    public InputStream download(String phoneName) throws Exception {
        return minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucket)
                        .object(phoneName)
                        .build()
        );
    }

    // 获取文件外链
    public String getPhotoUrl(String photoName) throws Exception {
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .bucket(bucket)
                        .object(photoName)
                        .method(Method.GET)
                        .build()
        );
    }
}
